<%@ page import="java.util.Random" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="java.awt.*" %>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page import="java.io.IOException" %>
<%@page pageEncoding="UTF-8" language="java" %>
<%!
  public String makeRandom()
  {
    String code="";
    Random rand = new Random();
    for (int i=0;i<6;i++)
    {
      code=code+rand.nextInt(10);
    }
    return code;
  }
  public void makeImg(HttpServletResponse response) throws IOException {
    response.setContentType("image/jpeg");
        // 创建图像缓冲区
        BufferedImage bi = new BufferedImage(100, 40, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 100, 40);
        // 设置字体
        Font font = new Font("Arial", Font.BOLD, 24);
        g.setFont(font);
        g.setColor(Color.black);
        String code = makeRandom();
        g.drawString(code, 10, 30);
        // 绘制一些线段挡住数字
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
          g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
          g.drawLine(random.nextInt(100), random.nextInt(40), random.nextInt(100), random.nextInt(40));
        }
        g.dispose();
        // 输出图像
        Cookie cookie=new Cookie("code",code);
        cookie.setPath("/221210400201");
        response.addCookie(cookie);
        ImageIO.write(bi, "jpg", response.getOutputStream());
  }
%>
<%
  makeImg(response);
%>

